package com.qinghua.blog.controller;

import com.qinghua.blog.po.Comment;
import com.qinghua.blog.po.User;
import com.qinghua.blog.service.BlogService;
import com.qinghua.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @GetMapping("/comments/{id}")
    public String comments(@PathVariable Long id, Model model){

        List<Comment> comments=commentService.listCommentByBlogId(id);

        model.addAttribute("comments",comments);

        return "blog :: commentList";
    }

    @PostMapping("/comments")
    public String postComment(Comment comment, HttpSession session){

        User user=(User)session.getAttribute("user");
        if(user!=null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        }else {
            comment.setAvatar("https://picsum.photos/200/300");
        }
        comment.setBlog(blogService.getBlog(comment.getBlog().getId()));

        commentService.saveComment(comment);

        String url="/comments/"+comment.getBlog().getId();
        return "redirect:"+url;
    }
}
